# coding:utf-8
import pandas as pd
import tushare as ts
import matplotlib.pyplot as plt
import numpy as np
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)
pd.set_option('display.width', 1000)
pd.set_option('display.float_format', lambda x: '%.7f' % x)
pd.set_option('expand_frame_repr', False)
plt.rcParams["font.sans-serif"] = ["SimHei"]  # 用来显示中文
plt.rcParams["axes.unicode_minus"] = False  # 用来显示负号
import matplotlib.ticker as ticker
from tabulate import tabulate
from matplotlib.pyplot import MultipleLocator
# data = [['2022-06-28', 1011163.180+3090897.799, 801663.460+3067183.180, 803474, 3833400],
# ['2022-06-29', 979296.260+2983207.782, 914695.000+2962873.320, 858674, 3784200],
# ['2022-06-30', 983104.180+2991128.141, 869918.000+2957838.280, 832034, 3810840],
# ['2022-07-01', 990585.400 + 3007836.540, 772487.000+3003364.560, 840674, 3802200],
# ['2022-07-04', 995012.460 + 3038218.913, 750144.000+3030645.960	, 795074, 3847800],
# ['2022-07-05', 771279.250 + 3228808.148, 673544.000+2948823.920	, 803114, 3822720],
# ]
data = [
['2022-07-11', 4001617, 1213283, 815553, 1243720],
['2022-07-12', 3980071, 1201450, 831433, 1229400],
['2022-07-13', 3993582, 1216248, 828113, 1232720],
['2022-07-14', 4013414, 1238822, 814633, 1246200],
['2022-07-15', 4002868, 1230515, 836873, 1223960],
['2022-07-18', 4024467, 1249335, 812833, 1248000],
['2022-07-19', 4028282, 1252634, 809319, 1252280],
['2022-07-20', 4046079, 1270875, 792073, 1268760],
['2022-07-21', 4027807, 1248331, 804033, 1256800],
['2022-07-22', 4029566, 1261856, 818833, 1242000],
['2022-07-25', 4013922, 1246198, 832673, 1227800],
['2022-07-26', 4037737, 1271709, 813913, 1246920]
]


total_value_df = pd.DataFrame(data=data, columns=['date', 'stock_total_value', 'stock_holding_value',
                                                  'future_dynamic_equity', 'future_holding_value'])


print(total_value_df)
total_value_df_copy = total_value_df.copy().rename(columns={'date': '日期', 'stock_total_value': '股票总资产',
                                                   'stock_holding_value': '股票市值',
                                                   'future_dynamic_equity': '期货动态权益',
                                                   'future_holding_value': '期货价值'})

fig, ax = plt.subplots()
# ax.xaxis.set_major_locator(ticker.MultipleLocator(6))
y_major_locator = MultipleLocator(0.003)
ax.yaxis.set_major_locator(y_major_locator)
plt.xticks(rotation=0, fontsize=7)
# plt.yticks(fontsize=8)
total_value_df['ratio1'] = (total_value_df['stock_total_value'] + total_value_df['future_dynamic_equity'])/(4005178+817304)
total_value_df['ratio2'] = (total_value_df['stock_total_value'] + total_value_df['future_dynamic_equity'])/(5000000)
print(total_value_df)
total_value_df_copy['新比例'] = total_value_df['ratio1']
total_value_df_copy['延续比例'] = total_value_df['ratio2']

token = "852ca49486f26aca6aab56d77f4ef50f0176983cbf3a0a1b6cc31d00"
# pro = ts.pro_api(token)
tushare_api = ts.pro_api(token)
start_date = total_value_df['date'].min().replace('-', '')
end_date = total_value_df['date'].max().replace('-', '')
print(start_date, end_date)
df = tushare_api.index_daily(ts_code='000905.SH', start_date=start_date, end_date=end_date,
                             )[['trade_date', 'close']].sort_values(by=['trade_date'])
df['trade_date'] = pd.to_datetime(df['trade_date']).dt.strftime('%Y-%m-%d')
# print(df)
merge_df = pd.merge(total_value_df_copy, df, left_on=['日期'], right_on=['trade_date'], how='left')
merge_df['指数变化速度'] = merge_df['close'].pct_change()
merge_df['股票变化速度'] = merge_df['股票市值'].pct_change()
merge_df['超额收益(中证500)'] = merge_df['股票变化速度'] - merge_df['指数变化速度']
print(tabulate(merge_df, headers='keys', tablefmt='psql', floatfmt=".4f"))
merge_df.drop(columns=['trade_date', 'close', '股票变化速度', '指数变化速度'], inplace=True)


display_cols = ['日期', '股票总资产', '股票市值', '期货动态权益',
                '期货价值', '超额收益(中证500)', '新比例', '延续比例']

# headers='keys'
print(tabulate(merge_df[display_cols], headers='keys', tablefmt='psql', floatfmt=".4f"))
plt.plot(total_value_df['date'], total_value_df['ratio1'], label='新比例')
plt.plot(total_value_df['date'], total_value_df['ratio2'], label='延续比例')
# plt.plot(total_value_df['date'], total_value_df['stock_holding_value'], label='stock_holding_value')
# plt.plot(total_value_df['date'], total_value_df['future_dynamic_equity'], label='future_dynamic_equity')
# plt.plot(total_value_df['date'], total_value_df['future_holding_value'], label='future_holding_value')
# plt.text('2022-06-29', 1000000, 'fffffffff',
#          fontsize=15, wrap=False)
# print(total_value_df.iloc[-1].to_dict())

plt.legend()
plt.show()










